<?php
/**
 * Created by PhpStorm.
 * User: dell
 * Date: 2018/4/30
 * Time: 14:45
 */

namespace app\common\lib;


use JiGuang\JSMS;
use think\Cache;
use think\Loader;
use think\Log;
Loader::import('jgms.JSMS', EXTEND_PATH, '.php');

class Jgms
{
    const LOG_TPL = "alidayu:";
    /**
     * 静态变量保存全局的实例
     * @var null
     */
    private static $_instance = null;

    /**
     * 私有的构造方法
     */
    public function __construct()
    {

    }

    public static function getInstance() {
        if (is_null(self::$_instance)) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    /**
     * @param $phone
     * @param int $type 0-注册验证码
     * @return bool
     */
    public function setSmsIndentify($phone,$type=0) {
        try{
            $app_key = config("jgms.appKey");
            $master_secret = config("jgms.masterSecret");
            if ($type == 0) {
                $temp_id = config("jgms.register_temp_id");
            }
            $client = new JSMS($app_key,$master_secret, [ 'disable_ssl' => true ]);
            $response = $client->sendCode($phone, $temp_id);
            if ($response['http_code'] == 200) {
                Cache::set("regCode",array("msg_id"=>$response['body']['msg_id'],'phone'=>$phone,'time'=>time()));
                return true;
            }
        }catch (\Exception $e) {
            //记录日志
            Log::write(self::LOG_TPL."set-----".$e->getMessage());
            return false;
        }
    }

    /**
     * @param $code 验证码
     * @param $phone 手机号
     */
    public function checkCode($code,$phone){
        if (empty($code)) {
            return false;
        }
        $regCode = Cache::get("regCode");
        if ($regCode['phone'] != $phone) {
            return false;
        }
        if ((time() - $regCode['time']) > 120) {
            return false;
        }
        $app_key = config("jgms.appKey");
        $master_secret = config("jgms.masterSecret");
        $client = new JSMS($app_key,$master_secret,array('disable_ssl' => true));
        $res = $client->checkCode($regCode['msg_id'], $code);

        if ($res['body']['is_valid'] == false && $res['http_code'] == 403) {
            return false;
        } else {
            return true;
        }
    }
}